import React, { useRef, useEffect, useState } from 'react';

interface MediaDeviceInfo {
  deviceId: string;
  kind: string;
  label: string;
}

const VideoCapture: React.FC = () => {
  // 引用DOM元素
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  
  // 状态管理
  const [audioInputDevices, setAudioInputDevices] = useState<MediaDeviceInfo[]>([]);
  const [audioOutputDevices, setAudioOutputDevices] = useState<MediaDeviceInfo[]>([]);
  const [videoDevices, setVideoDevices] = useState<MediaDeviceInfo[]>([]);
  const [selectedAudioInput, setSelectedAudioInput] = useState<string>('');
  const [selectedAudioOutput, setSelectedAudioOutput] = useState<string>('');
  const [selectedVideoInput, setSelectedVideoInput] = useState<string>('');
  const [selectedFilter, setSelectedFilter] = useState<string>('none');
  const [mediaStream, setMediaStream] = useState<MediaStream | null>(null);

  // 初始化设备列表和媒体流
  useEffect(() => {
    // 获取设备列表
    const enumerateDevices = async () => {
      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        
        const audioInputs: MediaDeviceInfo[] = [];
        const audioOutputs: MediaDeviceInfo[] = [];
        const videoInputs: MediaDeviceInfo[] = [];

        devices.forEach(device => {
          if (device.kind === 'audioinput') {
            audioInputs.push(device);
          } else if (device.kind === 'audiooutput') {
            audioOutputs.push(device);
          } else if (device.kind === 'videoinput') {
            videoInputs.push(device);
          }
        });

        setAudioInputDevices(audioInputs);
        setAudioOutputDevices(audioOutputs);
        setVideoDevices(videoInputs);

        // 设置默认设备
        if (audioInputs.length > 0) {
          setSelectedAudioInput(audioInputs[0].deviceId);
        }
        if (audioOutputs.length > 0) {
          setSelectedAudioOutput(audioOutputs[0].deviceId);
        }
        if (videoInputs.length > 0) {
          setSelectedVideoInput(videoInputs[0].deviceId);
        }
      } catch (error) {
        console.error('获取设备列表失败:', error);
      }
    };

    // 初始化设备和媒体流
    const initMedia = async () => {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.error('浏览器不支持getUserMedia');
        return;
      }

      try {
        // 获取设备列表
        await enumerateDevices();
        
        // 获取媒体流
        const constraints: MediaStreamConstraints = {
          video: true,
          audio: true
        };

        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        setMediaStream(stream);

        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      } catch (error) {
        console.error('获取媒体流失败:', error);
      }
    };

    initMedia();

    // 组件卸载时释放媒体流
    return () => {
      if (mediaStream) {
        mediaStream.getTracks().forEach(track => track.stop());
      }
    };
  }, []);

  // 切换媒体设备
  const handleDeviceChange = async (kind: string, deviceId: string) => {
    // 释放当前媒体流
    if (mediaStream) {
      mediaStream.getTracks().forEach(track => track.stop());
    }

    try {
      // 根据选择的设备创建新的约束
      const constraints: MediaStreamConstraints = {
        video: kind === 'videoinput' ? { deviceId } : selectedVideoInput ? { deviceId: selectedVideoInput } : true,
        audio: kind === 'audioinput' ? { deviceId } : selectedAudioInput ? { deviceId: selectedAudioInput } : true
      };

      // 获取新的媒体流
      const stream = await navigator.mediaDevices.getUserMedia(constraints);
      setMediaStream(stream);

      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }
    } catch (error) {
      console.error('切换设备失败:', error);
    }
  };

  // 处理音频输入设备变化
  const handleAudioInputChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const deviceId = e.target.value;
    setSelectedAudioInput(deviceId);
    handleDeviceChange('audioinput', deviceId);
  };

  // 处理视频输入设备变化
  const handleVideoInputChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const deviceId = e.target.value;
    setSelectedVideoInput(deviceId);
    handleDeviceChange('videoinput', deviceId);
  };

  // 处理滤镜变化
  const handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedFilter(e.target.value);
  };

  // 截取视频画面
  const takeSnapshot = () => {
    if (!canvasRef.current || !videoRef.current) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    if (ctx) {
      // 设置canvas尺寸
      canvas.width = 320;
      canvas.height = 240;
      
      // 绘制视频帧到canvas
      ctx.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
    }
  };

  return (
    <div className="video-capture-container">
      <h1>WebRTC 视频截图演示</h1>
      
      {/* 设备选择区域 */}
      <div className="select-container">
        <div className="select-group">
          <label htmlFor="audioSource">Audio input source: </label>
          <select 
            id="audioSource" 
            value={selectedAudioInput} 
            onChange={handleAudioInputChange}
          >
            {audioInputDevices.map(device => (
              <option key={device.deviceId} value={device.deviceId}>
                {device.label || `Audio Input ${audioInputDevices.indexOf(device) + 1}`}
              </option>
            ))}
          </select>
        </div>

        <div className="select-group">
          <label htmlFor="audioOutput">Audio output destination: </label>
          <select 
            id="audioOutput" 
            value={selectedAudioOutput} 
            onChange={(e) => setSelectedAudioOutput(e.target.value)}
          >
            {audioOutputDevices.map(device => (
              <option key={device.deviceId} value={device.deviceId}>
                {device.label || `Audio Output ${audioOutputDevices.indexOf(device) + 1}`}
              </option>
            ))}
          </select>
        </div>

        <div className="select-group">
          <label htmlFor="videoSource">Video source: </label>
          <select 
            id="videoSource" 
            value={selectedVideoInput} 
            onChange={handleVideoInputChange}
          >
            {videoDevices.map(device => (
              <option key={device.deviceId} value={device.deviceId}>
                {device.label || `Video Input ${videoDevices.indexOf(device) + 1}`}
              </option>
            ))}
          </select>
        </div>

        <div className="select-group">
          <label htmlFor="filter">Filter: </label>
          <select 
            id="filter" 
            value={selectedFilter} 
            onChange={handleFilterChange}
          >
            <option value="none">none</option>
            <option value="blur">模糊</option>
            <option value="grayscale">灰度</option>
            <option value="invert">反转</option>
            <option value="sepia">褐色</option>
            <option value="saturate">饱和度</option>
            <option value="hue-rotate">色相旋转</option>
            <option value="opacity">透明度</option>
            <option value="brightness">亮度</option>
            <option value="contrast">对比度</option>
            <option value="drop-shadow">阴影</option>
          </select>
        </div>
      </div>

      {/* 视频和截图区域 */}
      <div className="video-container">
        <video 
          ref={videoRef} 
          autoPlay 
          playsInline 
          className={selectedFilter}
          style={{
            width: '320px',
            height: '240px',
          }}
        />
        
        <div className="controls">
          <button onClick={takeSnapshot}>
            截取视频中的图片
          </button>
        </div>

        <div className="canvas-container">
          <canvas ref={canvasRef}></canvas>
        </div>
      </div>

      {/* 样式 */}
      <style jsx>{`
        .video-capture-container {
          max-width: 800px;
          margin: 0 auto;
          padding: 20px;
        }
        
        .select-container {
          margin-bottom: 20px;
        }
        
        .select-group {
          margin-bottom: 15px;
        }
        
        select {
          margin-left: 10px;
          padding: 5px;
        }
        
        video {
          border: 1px solid #ccc;
        }
        
        button {
          margin: 10px 0;
          padding: 8px 16px;
          background-color: #007bff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
        }
        
        button:hover {
          background-color: #0056b3;
        }
        
        canvas {
          border: 1px solid #ccc;
          margin-top: 10px;
        }
        
        /* 滤镜效果 */
        .none {
          filter: none;
        }
        
        .blur {
          filter: blur(3px);
        }
        
        .grayscale {
          filter: grayscale(1);
        }
        
        .invert {
          filter: invert(1);
        }
        
        .sepia {
          filter: sepia(1);
        }
        
        .saturate {
          filter: saturate(50%);
        }
        
        .hue-rotate {
          filter: hue-rotate(920deg);
        }
        
        .opacity {
          filter: opacity(20%);
        }
        
        .brightness {
          filter: brightness(150%);
        }
        
        .contrast {
          filter: contrast(200%);
        }
        
        .drop-shadow {
          filter: drop-shadow(8px 8px 10px gray);
        }
      `}</style>
    </div>
  );
};

export default VideoCapture;